<template>
  <div class="body">
    <div class="login-box">
      <h3 style="color: darkred">用户登陆</h3>
      <el-form :model="loginForm" :rules="rules" ref="loginForm" label-width="100px">
        <el-form-item label="登陆名称" prop="username">
          <el-input v-model="loginForm.username"></el-input>
        </el-form-item>
        <el-form-item label="登陆密码" prop="password">
          <el-input type="password" v-model="loginForm.password"></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="grid-content bg-purple">
                <el-input type="text" v-model="loginForm.code"></el-input>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="grid-content bg-purple">
                <img :src="code" width="120px" height="40px"/>
              </div>
            </el-col>
          </el-row>
        </el-form-item>
        <el-row style="position: relative; left: -45px">
          <el-button type="primary" @click="submitForm('loginForm')" class="loginUser">登 陆</el-button>
          <el-button type="primary" @click="addUser">注 册</el-button>
          <el-button type="success" @click="shangJia">切换商家登入</el-button>
        </el-row>
      </el-form>
    </div>

    <!-- 添加用户的模态框 -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible">
      <el-form :model="userForm" :rules="rules" ref="userForm">
        <el-form-item label="用户名称" :label-width="formLabelWidth" prop="username">
          <el-input v-model="userForm.username" autocomplete="off" @input="selectName"></el-input>
          <span v-if="msg" class="error-message">{{ msg }}</span>
        </el-form-item>
        <el-form-item label="用户密码" :label-width="formLabelWidth" prop="password">
          <el-input type="password" v-model="userForm.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" :label-width="formLabelWidth" prop="iphone">
          <el-input v-model="userForm.iphone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户头像" :label-width="formLabelWidth">
          <el-upload
              class="avatar-uploader"
              action="http://localhost:9091/file/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
            <img v-if="userForm.src" :src="userForm.src" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelSubmit">取 消</el-button>
        <el-button type="primary" @click="addUsers">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import '@/css/UserAndAdmin.css';
import {setToken} from "@/utils/auth";
export default {
  name: "userLogin",
  data() {
    return {
      loginForm: {
        username: 'jack',
        password: '123',
        iphone: '',
        code: '',
        uuid: ''
      },
      userForm: {
        id: 0,
        username: '',
        password: '',
        iphone: '',
        src: '',
        isUserNameAvailable: true, // 用于控制用户名是否可用
      },
      isConfirmButtonDisabled: true, // 初始状态禁用“确定”按钮
      msg: '', // 用于显示错误信息的变量
      rules: {
        username: [
          {required: true, message: '请输入用户名称', trigger: 'blur'},
          {validator: this.checkNameAvailability, trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入用户密码', trigger: 'blur'},
          {min: 1, max: 9, message: '长度在 1 到 9 个字符', trigger: 'blur'}
        ],
        iphone: [
          {required: true, message: '请输入手机号', trigger: 'blur'},
          // {pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur'}
        ],
        code: [
          {required: true, message: '请输入验证码', trigger: 'blur'}
        ],
        src: [
          {required: true, message: '请上传头像', trigger: 'blur'}
        ]
      },
      code: '',
      dialogFormVisible: false,
      title: '添加用户',
      formLabelWidth: '120px'
    };
  },
  methods: {
    // --------------------------------图片上传-------------
    handleAvatarSuccess(res) {
      this.userForm.src = res.data;
    },
    beforeAvatarUpload(file) {
      // 检查文件类型是否为 JPG, PNG 或 WebP
      const isJPGorPNGorWebP = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/webp';
      const isLt2M = file.size / 1024 / 1024 < 2; // 检查文件大小是否小于 2MB

      if (!isJPGorPNGorWebP) {
        this.$message.error('上传头像图片只能是 JPG, PNG 或 WebP 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPGorPNGorWebP && isLt2M;
    },

    // --------------------------------验证码-------------
    initCodeImage() {
      this.$axios.get('http://localhost:9091/captcha/getVerifyCodeImage')
          .then(response => {
            if (response.data.code === 200) {
              this.code = response.data.data;
              this.loginForm.uuid = response.data.uuid;
            }
          })
    },

    // --------------------------------用户登入-------------
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.login();
        } else {
          console.log('验证失败!');
          return false;
        }
      });
    },
    // 提交登入
    login() {
      this.$axios({
        url: 'http://localhost:9091/user/login',
        method: 'POST',
        data: this.loginForm
      }).then(response => {
        if (response.data.code === 200) {
          // 登录成功，设置 cookie
          // document.cookie = "username=" + encodeURIComponent(this.loginForm.username) + "; path=/; max-age=" + (60 * 60 * 24 * 7); // 存储7天
          setToken(response.data.data)
          this.$message({
            type: 'success',
            message: response.data.msg
          });
          this.$router.push('/');
        } else {
          this.$message({
            type: 'error',
            message: response.data.msg
          });
        }
      }).catch(error => {
        console.error('请求失败:', error);
        this.$message.error('请求失败');
      });
    },

    shangJia() {
      this.$router.push('/adminLogin');
    },

    // --------------------------------用户注册-------------
    reset() {
      this.userForm.id = 0;
      this.userForm.username = '';
      this.userForm.password = '';
      this.userForm.iphone = '';
      this.userForm.src = '';
    },
    addUser() {
      this.dialogFormVisible = true;
    },
    addUsers(){
      if (!this.userForm.username || !this.userForm.password || !this.userForm.iphone || !this.userForm.src) {
        this.$message.error('请填写完整的用户信息');
        return;
      }
      this.$axios({
        url: 'http://localhost:9091/user/add',
        method: 'POST',
        data: this.userForm
      }).then(response => {
        if (response.data.code === 200) {
          this.$message({
            type: 'success',
            message: response.data.msg
          });
          this.dialogFormVisible = false;
          this.reset();
        } else {
          this.$message({
            type: 'error',
            message: response.data.msg
          });
        }
      })
    },
    cancelSubmit() {
      this.dialogFormVisible = false;
      this.resetUserForm();
      this.reset();
    },
    resetUserForm() {
      this.$refs.userForm.resetFields();
    },

    //   重名判断
    selectName() {
      if (this.userForm.username.trim() === '') {
        this.msg = '商家名称不能为空';
        this.userForm.isUserNameAvailable = true; // 假设空名称不可用
        this.isConfirmButtonDisabled = true; // 禁用按钮
        return;
      }
      this.$axios({
        method: 'post',
        url: 'http://localhost:9091/user/selectUserName',
        data: {username: this.userForm.sname}
      }).then((response) => {
        const data = response.data;
        if (data.code === 200) {
          this.msg = data.message;
          this.userForm.isUserNameAvailable = false;
          this.isConfirmButtonDisabled = true; // 禁用按钮
        } else {
          this.msg = "";
          this.userForm.isUserNameAvailable = true;
          this.isConfirmButtonDisabled = false; // 启用按钮
        }
      })
    },
    checkNameAvailability(rule, value, callback) {
      if (!this.userForm.isUserNameAvailable) {
        callback(new Error('该名字已存在，请重新输入'));
      } else {
        callback();
      }
    },
  },
  created() {
    this.initCodeImage();
  }
}
</script>

<style scoped>
.error-message {
  color: #a94442;
  font-size: 0.875em; /* 14px */
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.el-button {
  margin-left: 100px;
}

.loginUser {
  width: 120px;
}

.el-button + .el-button, .el-checkbox.is-bordered + .el-checkbox.is-bordered {
  margin-left: 5px;
}

.el-col-pull-0, .el-col-pull-1, .el-col-pull-10, .el-col-pull-11, .el-col-pull-12, .el-col-pull-13, .el-col-pull-14, .el-col-pull-15, .el-col-pull-16, .el-col-pull-17, .el-col-pull-18, .el-col-pull-19, .el-col-pull-2, .el-col-pull-20, .el-col-pull-21, .el-col-pull-22, .el-col-pull-23, .el-col-pull-24, .el-col-pull-3, .el-col-pull-4, .el-col-pull-5, .el-col-pull-6, .el-col-pull-7, .el-col-pull-8, .el-col-pull-9, .el-col-push-0, .el-col-push-1, .el-col-push-10, .el-col-push-11, .el-col-push-12, .el-col-push-13, .el-col-push-14, .el-col-push-15, .el-col-push-16, .el-col-push-17, .el-col-push-18, .el-col-push-19, .el-col-push-2, .el-col-push-20, .el-col-push-21, .el-col-push-22, .el-col-push-23, .el-col-push-24, .el-col-push-3, .el-col-push-4, .el-col-push-5, .el-col-push-6, .el-col-push-7, .el-col-push-8, .el-col-push-9, .el-row, .el-upload-dragger, .el-upload-list__item {
  position: relative;
  left: -10px;
}
</style>